<template>
  <div class="dict-index">
    <div class="dict-sear" v-if="isShowSear">
      <el-form size="mini" inline>
        <el-form-item label="关键字">
          <el-input
            placeholder="关键字检索(名称)"
            v-model="searParams.keyword"
          ></el-input>
        </el-form-item>
        <el-form-item label="创建人">
          <el-select
            v-model="searParams.createBy"
            size="mini"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in createByList"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-select
            v-model="searParams.enable"
            size="mini"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in enableList"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="修改人">
          <el-select
            v-model="searParams.updateBy"
            size="mini"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in updateByList"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="createDate"
            style="width: 300px"
            size="mini"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="center"
            @change="selectDate"
          >
          </el-date-picker>
        </el-form-item>
        <el-button size="mini" type="primary" @click="exeSear">查询</el-button>
        <el-button size="mini" @click="initSearParams()">重置</el-button>
      </el-form>
    </div>
    <div class="dict-oper">
      <div class="dict-oper-left">
        <el-button
          type="primary"
          size="mini"
          plain
          icon="el-icon-plus"
          @click="preAdd"
          >新增</el-button
        >
        <el-button
          type="success"
          size="mini"
          plain
          icon="el-icon-edit"
          @click="modifyBatch()"
          >修改</el-button
        >
        <el-button
          type="danger"
          size="mini"
          plain
          icon="el-icon-delete"
          @click="removeBatch"
        >
          删除</el-button
        >
      </div>
      <div class="dict-oper-right">
        <el-button
          icon="el-icon-search"
          size="mini"
          circle
          @click="isShowSear = !isShowSear"
        ></el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          circle
          @click="exeSear()"
        ></el-button>
      </div>
    </div>
    <div class="dict-list">
      <el-table
        stripe
        highlight-current-row
        v-if="isRefreshTable"
        :data="dictTypePage.list"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        :default-expand-all="isExpand"
        tooltip-effect="dark"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @selection-change="modifySelect"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <!-- <el-table-column prop="id" label="ID" sortable width="180">
      </el-table-column> -->
        <el-table-column prop="name" label="名称"> </el-table-column>
        <el-table-column prop="type" label="类型">
          <template slot-scope="scope">
            <el-button @click="openRecord(scope.row)" type="text">{{
              scope.row.type
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="createTenant" label="创建人" align="left">
          <template slot-scope="scope">
            {{ scope.row.createTenant.username }}
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="updateTenant"
          label="修改人"
          align="left"
          width="150"
        >
          <template slot-scope="scope">
            {{ scope.row.updateTenant.username }}
          </template>
        </el-table-column> -->
        <el-table-column
          prop="level"
          label="是否启用"
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.enable"
              active-value="1"
              inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
              @change="modifyEnable(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="left">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          align="left"
          width="150"
        >
        </el-table-column>
        <!-- <el-table-column prop="updateTime" label="修改时间" align="left" width="150">
        </el-table-column> -->
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <el-button @click="openRecord(scope.row)" type="text" size="small"
              >查看</el-button
            >
            <el-button type="text" size="small" @click="modifySingle(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" size="small" @click="removeSingle(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="page"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="dictTypePage.totalCount"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="dictTypePage.pageSize"
        @current-change="modifyOffset"
        @size-change="modifyLimit"
      >
      </el-pagination>
    </div>
    <AddTypeComp
      v-if="isShowAddType"
      :enables="enableList"
      @submit="submitAddType"
      @close="closeAddType"
    />
    <EditTypeComp
      v-if="isShowEditType"
      :data="singleData"
      :enables="enableList"
      @submit="submitEditType"
      @close="closeEditType"
    />

    <Record v-if="isShowRecord" :data="singleData" @close="closeRecord()" />
  </div>
</template>

<script>
import { isNotEmpty, isEmpty, isNotNull, isNull } from "@/utils/validate";
import {
  list,
  listCreateBy,
  listUpdateBy,
  change,
  create,
  deleteByIds,
  queryById,
} from "@/api/dictType";
import { DICT_TYPE } from "@/utils/dict";
import AddTypeComp from "./type/addComp.vue";
import EditTypeComp from "./type/editComp.vue";
import Record from "./record.vue";

export default {
  components: {},
  data() {
    return {
      isShowSear: true,
      isRefreshTable: true,
      isShowAddType: false,
      isShowEditType: false,
      isShowRecord: false,
      isExpand: true,
      createByList: [],
      updateByList: [],
      searParams: {},
      createDate: "",
      dictTypePage: {},
      enableList: [],
      selectItems: [],
      selectIds: [],
      singleData: {},
    };
  },
  components: {
    AddTypeComp,
    EditTypeComp,
    Record,
  },
  created() {
    this.initSearParams();
    this.exeSear();
    this.listCreateBy();
    this.listUpdateBy();
    this.getEnable();
  },
  mounted() {},
  methods: {
    /**
     * 初始化搜索参数
     */
    initSearParams() {
      this.searParams = {
        offset: 0,
        limit: 5,
        fromTime: "",
        toTime: "",
        keyword: "",
      };
    },
    /**
     * 查询创建人列表
     */
    listCreateBy() {
      listCreateBy().then((res) => {
        if (res.code === 0 && res.data != null) {
          this.createByList = res.data;
        }
      });
    },
    /**
     * 查询修改人列表
     */
    listUpdateBy() {
      listUpdateBy().then((res) => {
        if (res.code === 0 && res.data != null) {
          this.updateByList = res.data;
        }
      });
    },
    /**
     * 查询启用/禁用
     */
    getEnable() {
      this.$store.dispatch("dict/getByType", DICT_TYPE.ENABLE).then((res) => {
        if (res.code === 0) {
          this.enableList = res.data;
        }
      });
    },
    /**
     * 执行搜索
     */
    exeSear() {
      list(this.searParams).then((res) => {
        if (res.code === 0) {
          this.dictTypePage = res.data;
        }
      });
    },
    /**
     * 展开/折叠
     */
    exband() {
      this.isRefreshTable = false;
      this.isExpand = !this.isExpand;
      this.$nextTick(() => {
        this.isRefreshTable = true;
      });
    },
    /**
     * 选择时间
     */
    selectDate(val) {
      this.searParams.fromTime = val[0];
      this.searParams.toTime = val[1];
    },
    /**
     * 页码改变
     */
    modifyOffset(val) {
      this.searParams.offset = val;
      this.exeSear();
    },
    /**
     * 页数改变
     */
    modifyLimit(val) {
      this.searParams.limit = val;
      this.exeSear();
    },
    /**
     * 修改启用状态
     */
    modifyEnable(val) {
      this.doModify({
        id: val.id,
        enable: val.enable,
      });
    },
    /**
     * 单修
     */
    modifySingle(val) {
      this.preModify([val]);
    },
    /**
     * 批修
     */
    modifyBatch() {
      this.preModify(this.selectItems);
    },
    /**
     * 预修改
     */
    preModify(dictTypeForms) {
      if (dictTypeForms == null || dictTypeForms.length != 1) {
        this.$message({
          message: "请选择一个字典类型",
          type: "warning",
        });
        return;
      }
      const dictTypeForm = dictTypeForms[0];
      queryById(dictTypeForm.id).then((res) => {
        console.log(res);
        if (res.code === 0) {
          this.getEnable();
          this.singleData = res.data;
          this.isShowEditType = true;
        } else {
          this.$message.error("同步字典类型失败");
        }
      });
    },
    /**
     * 关闭修改对话框
     */
    closeEditType() {
      this.isShowEditType = false;
    },
    /**
     * 提交修改
     */
    submitEditType(val) {
      this.doModify(val);
    },
    /**
     * 执行修改操作
     */
    doModify(val) {
      change(val).then((res) => {
        if (res.code === 0) {
          this.exeSear();
          this.isShowEditType = false;
          this.$message({
            message: "修改字典类型成功",
            type: "success",
          });
        } else {
          this.$message.error("修改字典类型失败");
        }
      });
    },
    /**
     * 表格选择改变
     */
    modifySelect(val) {
      this.selectItems = [];
      this.selectIds = [];
      for (let i = 0; i < val.length; i++) {
        this.selectItems.push(val[i]);
        this.selectIds.push(val[i].id);
      }
    },
    /**
     * 预添加
     */
    preAdd() {
      this.getEnable();
      this.isShowAddType = true;
    },
    /**
     * 关闭添加字典类型对话框
     */
    closeAddType() {
      this.isShowAddType = false;
    },
    /**
     * 提交添加字典类型
     */
    submitAddType(dictTypeForm) {
      create(dictTypeForm).then((res) => {
        if (res.code === 0 && res.data) {
          this.exeSear();
          this.isShowAddType = false;
          this.$message({
            message: "添加字典类型成功",
            type: "success",
          });
        } else {
          this.$message.error("添加字典类型失败");
        }
      });
    },
    /**
     * 单删
     */
    removeSingle(val) {
      this.doRemove([val.id]);
    },
    /**
     * 批删
     */
    removeBatch() {
      this.doRemove(this.selectIds);
    },
    /**
     * 执行删除
     */
    doRemove(dictTypeIds) {
      if (isEmpty(dictTypeIds)) {
        this.$message("未选中字典类型");
        return;
      }
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteByIds(dictTypeIds).then((res) => {
            if (res.code === 0) {
              this.exeSear();
              this.$message({
                message: "删除字典类型成功",
                type: "success",
              });
            } else {
              this.$message.error("删除字典类型失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /**
     * 打开字典数据
     */
    openRecord(val) {
      this.singleData = val;
      this.isShowRecord = true;
    },
    /**
     * 关闭字典数据
     */
    closeRecord() {
      this.isShowRecord = false;
    },
  },
};
</script>

<style>
.dict-index {
  height: auto;
  margin: 1%;
  display: flex;
  flex-direction: column;
}

.dict-oper {
  margin: 12px 0 12px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.dict-list {
  text-align: center;
}
</style>
